"""工作日节假日"""

import datetime
from datetime import timedelta, date
from json import loads
from multiprocessing import Pool, freeze_support
from urllib.request import urlopen


def daterange(start_date, end_date, fmt='%Y%m%d'):
    # stole from https://stackoverflow.com/a/1060330
    # generate dates from start_date to end_date

    _dates = []
    for n in range(int((end_date - start_date).days)):
        _dates.append(start_date + timedelta(n))

    return [x.strftime(fmt) for x in _dates]


def singleday(_date: str):
    mapper = {0: 'workday', 1: 'dayoff', 2: 'dayoff'}
    url = 'http://api.goseek.cn/Tools/holiday?date=' + _date
    dct = loads(urlopen(url).read().decode('utf-8'))
    print(f'{_date}: {mapper[dct["data"]]}')
    return mapper[dct['data']]


def singleyear(year: int, kernels=4):
    start_date = date(year, 1, 1)
    end_date = date(year+1, 1, 1)
    year_days = daterange(start_date, end_date)
    pool = Pool(kernels)
    judge_days = pool.map(singleday, year_days)
    return list(zip(year_days, judge_days))


def writeout(year: int, outfile=None, kernels=4):
    if outfile is None:
        outfile = 'year-%d.txt' % year
    lst = singleyear(year, kernels)
    with open(outfile, 'w', encoding='UTF-8') as f:
        f.write('Workday:\n')
        for d, j in lst:
            if j == 'workday':
                f.write(datetime.datetime.strptime(
                    d, '%Y%m%d').strftime('%Y-%m-%d\n'))

        f.write('\n')

        f.write('Dayoff:\n')
        for d, j in lst:
            if j == 'dayoff':
                f.write(datetime.datetime.strptime(
                    d, '%Y%m%d').strftime('%Y-%m-%d\n'))


if __name__ == '__main__':
    freeze_support()
    writeout(int(input('Input year (4 digits): ')), kernels=20)
